package com.kcs.fxmargin.action;

import java.io.File;
import java.io.FileOutputStream;
import java.util.ResourceBundle;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.upload.FormFile;

import com.kcs.common.utils.Constant;
import com.kcs.common.utils.PropsUtils;
import com.kcs.common.utils.commonUtils;
import com.kcs.fxmargin.action.form.ImportRateActionForm;
import com.kcs.fxmargin.action.form.LoginActionForm;
import com.kcs.fxmargin.service.ImportRateService;

public class ImportRateAction extends FXAction {
	private Logger log = Logger.getLogger(Constant.LOG_FX);
	private Logger logRetad = Logger.getLogger(Constant.LOG_IMPORT_RATE);
	
	@Override
	public ActionForward process(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		
		logRetad.info("ImportRateAction : Start");
		log.debug("ImportRateAction : Start");
		
		ImportRateActionForm bean = null;
		
		
		LoginActionForm userInfo = (LoginActionForm) request.getSession().getAttribute(Constant.LOGIN_DATA_SESSION);
		try{
			
			bean = (ImportRateActionForm)form;

			logRetad.info("bean.getTranCode = " + bean.getTranCode());
			log.debug("bean.getTranCode = " + bean.getTranCode());
			bean.setUserLoginId(userInfo.getUserId());
			if(bean.getTranCode().equals("")){
				bean.resetForm();
			
			}else if(bean.getTranCode().equals("importRate")){
				importRate(bean,request);				
			}
			
			
		}catch(Exception e){
			logRetad.error(e);
			log.error(e);
			e.printStackTrace();
			request.setAttribute(Constant.ERR_ATTR, e.getMessage());
			
		}finally{
			if(bean != null){
				bean.setTranCode("");
			}
		}		

		logRetad.info("ImportRateAction : End");
		log.debug("ImportRateAction : End");

		return mapping.findForward("importRate");
	}
	
	private void importRate(ImportRateActionForm formBean, HttpServletRequest request)throws Exception{
		ImportRateService svc = new ImportRateService();
		ResourceBundle prop = null;

		logRetad.info("ImportRateAction : importRate : Start");
		log.debug("ImportRateAction : importRate : Start");
		
		try{
			prop = PropsUtils.getProps(Constant.PROP_CONFIG_SYSTEM);
			
			String subFolder 	= commonUtils.formatDate(new java.util.Date(), "yyyyMM");
			String createDt  	= commonUtils.formatDate(new java.util.Date(), "_yyyyMMdd_HHmmss");
			FormFile file 		= formBean.getFile();
			
			if( file.getFileSize()== 0){			      
		    	throw new Exception("Please specific file");
		    }
						
			String filePath =  prop.getObject("file_path_unix").toString()+File.separator+subFolder;//getServlet().getServletContext().getRealPath("/") +"upload";

			logRetad.info("filePath ->" + filePath);
			log.debug("filePath ->" + filePath);
			
			File folder = new File(filePath);
		    if(!folder.exists()){		    	
		    	folder.mkdirs();
		    }
		    
		    String fileName 	 = file.getFileName();
		   
            String newfileName   = fileName.substring(0,fileName.lastIndexOf("."));
            String extensionFile = fileName.substring(fileName.lastIndexOf("."),fileName.length());
                     newfileName = newfileName+createDt+extensionFile;
            
		    if(!("").equals(fileName)){  

		        File newFile = new File(filePath, newfileName);
	              
		        if(!newFile.exists()){
		          FileOutputStream fos = new FileOutputStream(newFile);
		          fos.write(file.getFileData());
		          fos.flush();
		          fos.close();
		          
		        } 
	        	int res = svc.importRate(newFile.getAbsolutePath(), formBean.getUserLoginId());
	        	if(res>0){
	        		request.setAttribute(Constant.ERR_ATTR, "Save Completed");
	        	}
	        	else{
	        		request.setAttribute(Constant.ERR_ATTR, "Save Fail");
	        	}
		    }
		    else{
		    	request.setAttribute(Constant.ERR_ATTR, "Save Fail");
		    }
		}
		catch(Exception e){
			logRetad.error(e);
			log.error(e);
			throw e;
		}		

		logRetad.info("ImportRateAction : importRate : End");
		log.debug("ImportRateAction : importRate : End");
	}

}
